<!DOCTYPE html>












  


<html class="theme-next mist use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">


























<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2">

<link rel="stylesheet" href="/css/main.css?v=7.0.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=7.0.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.ico?v=7.0.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.ico?v=7.0.0">


  <link rel="mask-icon" href="/images/logo.svg?v=7.0.0" color="#222">







<script id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '7.0.0',
    sidebar: {"position":"left","display":"hide","offset":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="注：本文转载自南轲梦 上篇文章《深入浅出Mybatis系列（六）—objectFactory、plugins、mappers简介与配置》简单地给mybatis的配置画上了一个句号。那么从本篇文章开始，将会介绍mapper映射文件的配置， 这是mybatis的核心之一，一定要学好。在mapper文件中，以mapper作为根节点，其下面可以配置的元素节点有： select, insert, updat">
<meta name="keywords" content="Mybatis,Source code">
<meta property="og:type" content="article">
<meta property="og:title" content="深入浅出Mybatis系列七-mapper映射文件配置之insert、update、delete">
<meta property="og:url" content="https://chloneda.github.io/blog/mybatis-7/index.html">
<meta property="og:site_name" content="Chloneda">
<meta property="og:description" content="注：本文转载自南轲梦 上篇文章《深入浅出Mybatis系列（六）—objectFactory、plugins、mappers简介与配置》简单地给mybatis的配置画上了一个句号。那么从本篇文章开始，将会介绍mapper映射文件的配置， 这是mybatis的核心之一，一定要学好。在mapper文件中，以mapper作为根节点，其下面可以配置的元素节点有： select, insert, updat">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2019-05-19T14:53:29.163Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="深入浅出Mybatis系列七-mapper映射文件配置之insert、update、delete">
<meta name="twitter:description" content="注：本文转载自南轲梦 上篇文章《深入浅出Mybatis系列（六）—objectFactory、plugins、mappers简介与配置》简单地给mybatis的配置画上了一个句号。那么从本篇文章开始，将会介绍mapper映射文件的配置， 这是mybatis的核心之一，一定要学好。在mapper文件中，以mapper作为根节点，其下面可以配置的元素节点有： select, insert, updat">



  <link rel="alternate" href="/rss2.html" title="Chloneda" type="application/atom+xml">




  <link rel="canonical" href="https://chloneda.github.io/blog/mybatis-7/">



<script id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>深入浅出Mybatis系列七-mapper映射文件配置之insert、update、delete | Chloneda</title>
  












  <noscript>
  <style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Chloneda</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <h1 class="site-subtitle" itemprop="description">简约的程序员</h1>
      
    
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">

    
    
    
      
    

    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">

    
    
    
      
    

    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">

    
    
    
      
    

    

    <a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">

    
    
    
      
    

    

    <a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-project">

    
    
    
      
    

    

    <a href="/project/" rel="section"><i class="menu-item-icon fa fa-fw fa-github"></i> <br>项目</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-about">

    
    
    
      
    

    

    <a href="/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i> <br>关于</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-links">

    
    
    
      
    

    

    <a href="/links/" rel="section"><i class="menu-item-icon fa fa-fw fa-link"></i> <br>友链</a>

  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>搜索</a>
        </li>
      
    </ul>
  

  
    

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://chloneda.github.io/blog/mybatis-7/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="chloneda">
      <meta itemprop="description" content="Less is more">
      <meta itemprop="image" content="/images/chloneda.jpeg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Chloneda">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">深入浅出Mybatis系列七-mapper映射文件配置之insert、update、delete

              
            
          </h2>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2019-05-19 22:53:29" itemprop="dateCreated datePublished" datetime="2019-05-19T22:53:29+08:00">2019-05-19</time>
            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/Mybatis/" itemprop="url" rel="index"><span itemprop="name">Mybatis</span></a></span>

                
                
              
            </span>
          

          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="post-meta-item-icon">
            <i class="fa fa-eye"></i>
             阅读次数： 
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>注：本文转载自<a href="https://www.cnblogs.com/dongying/p/4048828.html" target="_blank" rel="noopener">南轲梦</a></p>
<p>上篇文章《深入浅出Mybatis系列（六）—objectFactory、plugins、mappers简介与配置》简单地给mybatis的配置画上了一个句号。那么从本篇文章开始，将会介绍mapper映射文件的配置， 这是mybatis的核心之一，一定要学好。在mapper文件中，以mapper作为根节点，其下面可以配置的元素节点有： select, insert, update, delete, cache, cache-ref, resultMap, sql 。</p>
<p>本篇文章将简单介绍 insert, update, delete 的配置及使用，以后会对mybatis的源码进行深入讲解。</p>
<p>相信，看到insert, update, delete， 我们就知道其作用了，顾名思义嘛，myabtis 作为持久层框架，必须要对CRUD啊。</p>
<p>好啦，咱们就先来看看 insert, update, delete 怎么配置， 能配置哪些元素吧：</p>
<p>相关元素配置<br><figure class="highlight django"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br></pre></td><td class="code"><pre><span class="line"><span class="xml"><span class="meta">&lt;?xml version="1.0" encoding="UTF-8" ?&gt;</span>   </span></span><br><span class="line"><span class="xml"><span class="meta">&lt;!DOCTYPE mapper   </span></span></span><br><span class="line"><span class="xml">PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"  </span></span><br><span class="line"><span class="xml">"http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd"&gt; </span></span><br><span class="line"><span class="xml"></span></span><br><span class="line"><span class="xml"><span class="comment">&lt;!-- mapper 为根元素节点， 一个namespace对应一个dao --&gt;</span></span></span><br><span class="line"><span class="xml"><span class="tag">&lt;<span class="name">mapper</span> <span class="attr">namespace</span>=<span class="string">"com.dy.dao.UserDao"</span>&gt;</span></span></span><br><span class="line"><span class="xml"></span></span><br><span class="line"><span class="xml">    <span class="tag">&lt;<span class="name">insert</span></span></span></span><br><span class="line"><span class="xml">      <span class="comment">&lt;!-- </span></span></span><br><span class="line"><span class="xml">        1. id （必须配置）</span></span><br><span class="line"><span class="xml">        id是命名空间中的唯一标识符，可被用来代表这条语句。 </span></span><br><span class="line"><span class="xml">        一个命名空间（namespace） 对应一个dao接口, </span></span><br><span class="line"><span class="xml">        这个id也应该对应dao里面的某个方法（相当于方法的实现），因此id 应该与方法名一致 </span></span><br><span class="line"><span class="xml">　　　　--&gt;</span></span><br><span class="line"><span class="xml">      </span></span><br><span class="line"><span class="xml">      id="insertUser"</span></span><br><span class="line"><span class="xml">      </span></span><br><span class="line"><span class="xml">      <span class="comment">&lt;!-- </span></span></span><br><span class="line"><span class="xml">         2. parameterType （可选配置, 默认为mybatis自动选择处理）</span></span><br><span class="line"><span class="xml">         将要传入语句的参数的完全限定类名或别名， 如果不配置，</span></span><br><span class="line"><span class="xml">　　　　　 mybatis会通过ParameterHandler 根据参数类型默认选择合适的typeHandler进行处理</span></span><br><span class="line"><span class="xml">         parameterType 主要指定参数类型，可以是int, short, long, </span></span><br><span class="line"><span class="xml">　　　　　 string等类型，也可以是复杂类型（如对象）</span></span><br><span class="line"><span class="xml">　　　　--&gt;</span></span><br><span class="line"><span class="xml">      </span></span><br><span class="line"><span class="xml">      parameterType="com.demo.User"</span></span><br><span class="line"><span class="xml">      </span></span><br><span class="line"><span class="xml">      <span class="comment">&lt;!-- </span></span></span><br><span class="line"><span class="xml">         3. flushCache （可选配置，默认配置为true）</span></span><br><span class="line"><span class="xml">         将其设置为 true，任何时候只要语句被调用，都会导致本地缓存和二级缓存都会被清空，</span></span><br><span class="line"><span class="xml">         默认值：true（对应插入、更新和删除语句） </span></span><br><span class="line"><span class="xml">      --&gt;</span></span><br><span class="line"><span class="xml">      </span></span><br><span class="line"><span class="xml">      flushCache="true"</span></span><br><span class="line"><span class="xml">      </span></span><br><span class="line"><span class="xml">      <span class="comment">&lt;!-- </span></span></span><br><span class="line"><span class="xml">         4. statementType （可选配置，默认配置为PREPARED）</span></span><br><span class="line"><span class="xml">         STATEMENT，PREPARED 或 CALLABLE 的一个。这会让 MyBatis 分别使用 Statement，</span></span><br><span class="line"><span class="xml">         PreparedStatement 或 CallableStatement，默认值：PREPARED。 </span></span><br><span class="line"><span class="xml">      --&gt;</span></span><br><span class="line"><span class="xml">      </span></span><br><span class="line"><span class="xml">      statementType="PREPARED"</span></span><br><span class="line"><span class="xml">      </span></span><br><span class="line"><span class="xml">      <span class="comment">&lt;!-- </span></span></span><br><span class="line"><span class="xml">         5. keyProperty (可选配置， 默认为unset)</span></span><br><span class="line"><span class="xml">        （仅对 insert 和 update 有用）唯一标记一个属性，MyBatis 会通过 </span></span><br><span class="line"><span class="xml">         getGeneratedKeys 的返回值或者通过 insert 语句的 selectKey 子元素设置它的键值，</span></span><br><span class="line"><span class="xml">         默认：unset。如果希望得到多个生成的列，也可以是逗号分隔的属性名称列表。 </span></span><br><span class="line"><span class="xml">      --&gt;</span></span><br><span class="line"><span class="xml">      </span></span><br><span class="line"><span class="xml">      keyProperty=""</span></span><br><span class="line"><span class="xml">      </span></span><br><span class="line"><span class="xml">      <span class="comment">&lt;!-- </span></span></span><br><span class="line"><span class="xml">         6. keyColumn     (可选配置)</span></span><br><span class="line"><span class="xml">        （仅对 insert 和 update 有用）通过生成的键值设置表中的列名，这个设置仅在某些数据库</span></span><br><span class="line"><span class="xml">        （像 PostgreSQL）是必须的，当主键列不是表中的第一列的时候需要设置。</span></span><br><span class="line"><span class="xml">         如果希望得到多个生成的列，也可以是逗号分隔的属性名称列表。 </span></span><br><span class="line"><span class="xml">      --&gt;</span></span><br><span class="line"><span class="xml">      </span></span><br><span class="line"><span class="xml">      keyColumn=""</span></span><br><span class="line"><span class="xml">      </span></span><br><span class="line"><span class="xml">      <span class="comment">&lt;!-- </span></span></span><br><span class="line"><span class="xml">         7. useGeneratedKeys (可选配置， 默认为false)</span></span><br><span class="line"><span class="xml">        （仅对 insert 和 update 有用）这会令 MyBatis 使用 JDBC 的 </span></span><br><span class="line"><span class="xml">         getGeneratedKeys 方法来取出由数据库内部生成的主键（比如：像 MySQL 和 SQL Server </span></span><br><span class="line"><span class="xml">         这样的关系数据库管理系统的自动递增字段），默认值：false。  </span></span><br><span class="line"><span class="xml">      --&gt;</span></span><br><span class="line"><span class="xml">      </span></span><br><span class="line"><span class="xml">      useGeneratedKeys="false"</span></span><br><span class="line"><span class="xml">      </span></span><br><span class="line"><span class="xml">      <span class="comment">&lt;!-- </span></span></span><br><span class="line"><span class="xml">         8. timeout  (可选配置， 默认为unset, 依赖驱动)</span></span><br><span class="line"><span class="xml">         这个设置是在抛出异常之前，驱动程序等待数据库返回请求结果的秒数。默认值为 unset（依赖驱动）。 </span></span><br><span class="line"><span class="xml">      --&gt;</span></span><br><span class="line"><span class="xml">      timeout="20"&gt;</span></span><br><span class="line"><span class="xml"></span></span><br><span class="line"><span class="xml">    <span class="tag">&lt;<span class="name">update</span></span></span></span><br><span class="line"><span class="xml">      id="updateUser"</span></span><br><span class="line"><span class="xml">      parameterType="com.demo.User"</span></span><br><span class="line"><span class="xml">      flushCache="true"</span></span><br><span class="line"><span class="xml">      statementType="PREPARED"</span></span><br><span class="line"><span class="xml">      timeout="20"&gt;</span></span><br><span class="line"><span class="xml"></span></span><br><span class="line"><span class="xml">    <span class="tag">&lt;<span class="name">delete</span></span></span></span><br><span class="line"><span class="xml">      id="deleteUser"</span></span><br><span class="line"><span class="xml">      parameterType="com.demo.User"</span></span><br><span class="line"><span class="xml">      flushCache="true"</span></span><br><span class="line"><span class="xml">      statementType="PREPARED"</span></span><br><span class="line"><span class="xml">      timeout="20"&gt;</span></span><br><span class="line"><span class="xml"><span class="tag">&lt;/<span class="name">mapper</span>&gt;</span></span></span><br></pre></td></tr></table></figure></p>
<p>以上就是一个模板配置， 哪些是必要配置，哪些是根据自己实际需求，看一眼就知道了。</p>
<p>下面， 还是用第一篇文章《深入浅出Mybatis系列（一）—Mybatis入门》里面的demo来示例吧：</p>
<h1 id="User类"><a href="#User类" class="headerlink" title="User类"></a>User类</h1><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">User</span> &#123;</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> id;</span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line">    <span class="keyword">private</span> String password;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> age;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> deleteFlag;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//setter和getter方法省略...</span></span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="UserDao类"><a href="#UserDao类" class="headerlink" title="UserDao类"></a>UserDao类</h1><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title">UserDao</span> &#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">insertUser</span> (<span class="params">User user</span>)</span>;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">updateUser</span> (<span class="params">User user</span>)</span>;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">deleteUser</span> (<span class="params">User user</span>)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="userDao-xml"><a href="#userDao-xml" class="headerlink" title="userDao.xml"></a>userDao.xml</h1><figure class="highlight dust"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="xml"><span class="meta">&lt;?xml version="1.0" encoding="UTF-8" ?&gt;</span>   </span></span><br><span class="line"><span class="xml"><span class="meta">&lt;!DOCTYPE mapper   </span></span></span><br><span class="line"><span class="xml">PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"  </span></span><br><span class="line"><span class="xml">"http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd"&gt; </span></span><br><span class="line"><span class="xml"></span></span><br><span class="line"><span class="xml"><span class="tag">&lt;<span class="name">mapper</span> <span class="attr">namespace</span>=<span class="string">"com.dy.dao.UserDao"</span>&gt;</span></span></span><br><span class="line"><span class="xml">   </span></span><br><span class="line"><span class="xml">   <span class="comment">&lt;!-- 对应userDao中的insertUser方法，  --&gt;</span></span></span><br><span class="line"><span class="xml">   <span class="tag">&lt;<span class="name">insert</span> <span class="attr">id</span>=<span class="string">"insertUser"</span> <span class="attr">parameterType</span>=<span class="string">"com.dy.entity.User"</span>&gt;</span></span></span><br><span class="line"><span class="xml">           insert into user(id, name, password, age, deleteFlag) </span></span><br><span class="line"><span class="xml">               values(#</span><span class="template-variable">&#123;id&#125;</span><span class="xml"></span></span><br><span class="line"><span class="xml">			, #</span><span class="template-variable">&#123;name&#125;</span><span class="xml"></span></span><br><span class="line"><span class="xml">			, #</span><span class="template-variable">&#123;password&#125;</span><span class="xml"></span></span><br><span class="line"><span class="xml">			, #</span><span class="template-variable">&#123;age&#125;</span><span class="xml"></span></span><br><span class="line"><span class="xml">			, #</span><span class="template-variable">&#123;deleteFlag&#125;</span><span class="xml">)</span></span><br><span class="line"><span class="xml">   <span class="tag">&lt;/<span class="name">insert</span>&gt;</span></span></span><br><span class="line"><span class="xml">   </span></span><br><span class="line"><span class="xml">   <span class="comment">&lt;!-- 对应userDao中的updateUser方法 --&gt;</span></span></span><br><span class="line"><span class="xml">   <span class="tag">&lt;<span class="name">update</span> <span class="attr">id</span>=<span class="string">"updateUser"</span> <span class="attr">parameterType</span>=<span class="string">"com.dy.entity.User"</span>&gt;</span></span></span><br><span class="line"><span class="xml">           update user set name = #</span><span class="template-variable">&#123;name&#125;</span><span class="xml"></span></span><br><span class="line"><span class="xml">		, password = #</span><span class="template-variable">&#123;password&#125;</span><span class="xml"></span></span><br><span class="line"><span class="xml">		, age = #</span><span class="template-variable">&#123;age&#125;</span><span class="xml"></span></span><br><span class="line"><span class="xml">		, deleteFlag = #</span><span class="template-variable">&#123;deleteFlag&#125;</span><span class="xml"></span></span><br><span class="line"><span class="xml">               where id = #</span><span class="template-variable">&#123;id&#125;</span><span class="xml">;</span></span><br><span class="line"><span class="xml">   <span class="tag">&lt;/<span class="name">update</span>&gt;</span></span></span><br><span class="line"><span class="xml">    </span></span><br><span class="line"><span class="xml">   <span class="comment">&lt;!-- 对应userDao中的deleteUser 方法 --&gt;</span> </span></span><br><span class="line"><span class="xml">   <span class="tag">&lt;<span class="name">delete</span> <span class="attr">id</span>=<span class="string">"deleteUser"</span> <span class="attr">parameterType</span>=<span class="string">"com.dy.entity.User"</span>&gt;</span></span></span><br><span class="line"><span class="xml">           delete from user where id = #</span><span class="template-variable">&#123;id&#125;</span><span class="xml">;</span></span><br><span class="line"><span class="xml">   <span class="tag">&lt;/<span class="name">delete</span>&gt;</span></span></span><br><span class="line"><span class="xml"><span class="tag">&lt;/<span class="name">mapper</span>&gt;</span></span></span><br></pre></td></tr></table></figure>
<p>这样，一个简单的映射关系就建立了。仔细观察上面parameterType,  “com.dy.entity.User”，包名要是再长点呢，每次都这样写，写得蛋疼了。别忘了之前讲的 typeAliases（别名）， 那么这个地方，用上别名，岂不是技能跟蛋疼的长长的包名说拜拜了。好啦，咱们配上别名，在哪儿配？ 当然是在mybatis 的全局配置文件（我这儿名字是mybatis-conf.xml）， 不要认为是在mapper的配置文件里面配置哈。</p>
<h1 id="mybatis-conf-xml"><a href="#mybatis-conf-xml" class="headerlink" title="mybatis-conf.xml"></a>mybatis-conf.xml</h1><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">typeAliases</span>&gt;</span></span><br><span class="line">      <span class="comment">&lt;!--</span></span><br><span class="line"><span class="comment">      通过package, 可以直接指定package的名字， mybatis会自动扫描你指定包下面的javabean,</span></span><br><span class="line"><span class="comment">      并且默认设置一个别名，默认的名字为： javabean 的首字母小写的非限定类名来作为它的别名。</span></span><br><span class="line"><span class="comment">      也可在javabean 加上注解@Alias 来自定义别名， 例如： @Alias(user) </span></span><br><span class="line"><span class="comment">      &lt;package name="com.dy.entity"/&gt;</span></span><br><span class="line"><span class="comment">       --&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">typeAlias</span> <span class="attr">alias</span>=<span class="string">"user"</span> <span class="attr">type</span>=<span class="string">"com.dy.entity.User"</span>/&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">typeAliases</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>这样，一个别名就取好了，咱们可以把上面的 com.dy.entity.User 都直接改为user 了。 这多方便呀！</p>
<p>我这儿数据库用的是mysql, 我把user表的主键id 设置了自动增长， 以上代码运行正常， 那么问题来了（当然，我不是要问学挖掘机哪家强），我要是换成oracle数据库怎么办？ oracle 可是不支持id自增长啊？ 怎么办？请看下面：<br><figure class="highlight dust"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="xml"><span class="comment">&lt;!-- 对应userDao中的insertUser方法，  --&gt;</span></span></span><br><span class="line"><span class="xml">   <span class="tag">&lt;<span class="name">insert</span> <span class="attr">id</span>=<span class="string">"insertUser"</span> <span class="attr">parameterType</span>=<span class="string">"com.dy.entity.User"</span>&gt;</span></span></span><br><span class="line"><span class="xml">           <span class="comment">&lt;!-- oracle等不支持id自增长的，可根据其id生成策略，先获取id </span></span></span><br><span class="line"><span class="xml">           </span></span><br><span class="line"><span class="xml">        <span class="tag">&lt;<span class="name">selectKey</span> <span class="attr">resultType</span>=<span class="string">"int"</span> <span class="attr">order</span>=<span class="string">"BEFORE"</span> <span class="attr">keyProperty</span>=<span class="string">"id"</span>&gt;</span></span></span><br><span class="line"><span class="xml">              select seq_user_id.nextval as id from dual</span></span><br><span class="line"><span class="xml">        <span class="tag">&lt;/<span class="name">selectKey</span>&gt;</span></span></span><br><span class="line"><span class="xml">        </span></span><br><span class="line"><span class="xml">        --&gt;   </span></span><br><span class="line"><span class="xml">           insert into user(id, name, password, age, deleteFlag) </span></span><br><span class="line"><span class="xml">               values(#</span><span class="template-variable">&#123;id&#125;</span><span class="xml">, #</span><span class="template-variable">&#123;name&#125;</span><span class="xml">, #</span><span class="template-variable">&#123;password&#125;</span><span class="xml">, #</span><span class="template-variable">&#123;age&#125;</span><span class="xml">, #</span><span class="template-variable">&#123;deleteFlag&#125;</span><span class="xml">)</span></span><br><span class="line"><span class="xml">   <span class="tag">&lt;/<span class="name">insert</span>&gt;</span></span></span><br></pre></td></tr></table></figure></p>
<p>同理，如果我们在使用mysql的时候，想在数据插入后返回插入的id, 我们也可以使用 selectKey 这个元素：<br><figure class="highlight dust"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="xml"><span class="comment">&lt;!-- 对应userDao中的insertUser方法，  --&gt;</span></span></span><br><span class="line"><span class="xml">   <span class="tag">&lt;<span class="name">insert</span> <span class="attr">id</span>=<span class="string">"insertUser"</span> <span class="attr">parameterType</span>=<span class="string">"com.dy.entity.User"</span>&gt;</span></span></span><br><span class="line"><span class="xml">        <span class="comment">&lt;!-- </span></span></span><br><span class="line"><span class="xml">	oracle等不支持id自增长的，可根据其id生成策略，先获取id </span></span><br><span class="line"><span class="xml">        <span class="tag">&lt;<span class="name">selectKey</span> <span class="attr">resultType</span>=<span class="string">"int"</span> <span class="attr">order</span>=<span class="string">"BEFORE"</span> <span class="attr">keyProperty</span>=<span class="string">"id"</span>&gt;</span></span></span><br><span class="line"><span class="xml">              select seq_user_id.nextval as id from dual</span></span><br><span class="line"><span class="xml">        <span class="tag">&lt;/<span class="name">selectKey</span>&gt;</span></span></span><br><span class="line"><span class="xml">        --&gt; </span></span><br><span class="line"><span class="xml">        </span></span><br><span class="line"><span class="xml">        <span class="comment">&lt;!-- mysql插入数据后，获取id --&gt;</span></span></span><br><span class="line"><span class="xml">        <span class="tag">&lt;<span class="name">selectKey</span> <span class="attr">keyProperty</span>=<span class="string">"id"</span> <span class="attr">resultType</span>=<span class="string">"int"</span> <span class="attr">order</span>=<span class="string">"AFTER"</span> &gt;</span></span></span><br><span class="line"><span class="xml">               SELECT LAST_INSERT_ID() as id</span></span><br><span class="line"><span class="xml">        <span class="tag">&lt;/<span class="name">selectKey</span>&gt;</span></span></span><br><span class="line"><span class="xml">          </span></span><br><span class="line"><span class="xml">        insert into user(id, name, password, age, deleteFlag) </span></span><br><span class="line"><span class="xml">                values(#</span><span class="template-variable">&#123;id&#125;</span><span class="xml">, #</span><span class="template-variable">&#123;name&#125;</span><span class="xml">, #</span><span class="template-variable">&#123;password&#125;</span><span class="xml">, #</span><span class="template-variable">&#123;age&#125;</span><span class="xml">, #</span><span class="template-variable">&#123;deleteFlag&#125;</span><span class="xml">)</span></span><br><span class="line"><span class="xml">   <span class="tag">&lt;/<span class="name">insert</span>&gt;</span></span></span><br></pre></td></tr></table></figure></p>
<p>这儿，我们就简单提一下 <selectkey> 这个元素节点吧:<br><figure class="highlight django"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="xml"><span class="tag">&lt;<span class="name">selectKey</span></span></span></span><br><span class="line"><span class="xml">        <span class="comment">&lt;!-- </span></span></span><br><span class="line"><span class="xml">	selectKey 语句结果应该被设置的目标属性。如果希望得到多个生成的列，</span></span><br><span class="line"><span class="xml">	也可以是逗号分隔的属性名称列表。 </span></span><br><span class="line"><span class="xml">	--&gt;</span></span><br><span class="line"><span class="xml">        keyProperty="id"</span></span><br><span class="line"><span class="xml"></span></span><br><span class="line"><span class="xml">        <span class="comment">&lt;!-- </span></span></span><br><span class="line"><span class="xml">	结果的类型。MyBatis 通常可以推算出来，但是为了更加确定写上也不会有什么问题。</span></span><br><span class="line"><span class="xml">	MyBatis 允许任何简单类型用作主键的类型，包括字符串。如果希望作用于多个生成的列，</span></span><br><span class="line"><span class="xml">	则可以使用一个包含期望属性的 Object 或一个 Map。 </span></span><br><span class="line"><span class="xml">	--&gt;</span></span><br><span class="line"><span class="xml">        resultType="int"</span></span><br><span class="line"><span class="xml"></span></span><br><span class="line"><span class="xml">        <span class="comment">&lt;!-- </span></span></span><br><span class="line"><span class="xml">	这可以被设置为 BEFORE 或 AFTER。如果设置为 BEFORE，那么它会首先选择主键，</span></span><br><span class="line"><span class="xml">	设置 keyProperty 然后执行插入语句。如果设置为 AFTER，那么先执行插入语句，</span></span><br><span class="line"><span class="xml">	然后是 selectKey 元素 - 这和像 Oracle 的数据库相似，在插入语句内部可能有嵌入索引调用。 </span></span><br><span class="line"><span class="xml">	--&gt;</span></span><br><span class="line"><span class="xml">        order="BEFORE"</span></span><br><span class="line"><span class="xml"></span></span><br><span class="line"><span class="xml">        <span class="comment">&lt;!-- </span></span></span><br><span class="line"><span class="xml">	与前面相同，MyBatis 支持 STATEMENT，PREPARED 和 CALLABLE 语句的映射类型，</span></span><br><span class="line"><span class="xml">	分别代表 PreparedStatement 和 CallableStatement 类型。 </span></span><br><span class="line"><span class="xml">	--&gt;</span></span><br><span class="line"><span class="xml">        statementType="PREPARED"&gt;</span></span><br></pre></td></tr></table></figure></selectkey></p>
<p>好啦，本篇文章主要介绍了insert, update, delete的配置及用法。 下篇文章将介绍复杂的 select相关的配置及用法， 待这些都讲完后，会先根据源码分析一下mybatis的整个运行流程，然后再深入mybatis的用法。</p>
<hr>

      
    </div>

    

    
    
    

    

    
      
    
    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>您的支持是对我最大的鼓励</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById(&quot;QR&quot;); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.jpg" alt="chloneda 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="chloneda 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
      <div>
        



  



<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>chloneda</li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    
    <a href="https://chloneda.github.io/blog/mybatis-7/" title="深入浅出Mybatis系列七-mapper映射文件配置之insert、update、delete">https://chloneda.github.io/blog/mybatis-7/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fa fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！</li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Mybatis/" rel="tag"># Mybatis</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/mybatis-4/" rel="next" title="深入浅出Mybatis系列四-配置详解之typeAliases别名（mybatis源码篇）">
                <i class="fa fa-chevron-left"></i> 深入浅出Mybatis系列四-配置详解之typeAliases别名（mybatis源码篇）
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/mybatis-6/" rel="prev" title="深入浅出Mybatis系列六-objectFactory、plugins、mappers简介与配置">
                深入浅出Mybatis系列六-objectFactory、plugins、mappers简介与配置 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>
  
  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/chloneda.jpeg" alt="chloneda">
            
              <p class="site-author-name" itemprop="name">chloneda</p>
              <p class="site-description motion-element" itemprop="description">Less is more</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">31</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">16</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">16</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          
            <div class="feed-link motion-element">
              <a href="/rss2.html" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://github.com/chloneda" title="GitHub &rarr; https://github.com/chloneda" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://twitter.com/chloneda" title="Twitter &rarr; https://twitter.com/chloneda" rel="noopener" target="_blank"><i class="fa fa-fw fa-twitter"></i>Twitter</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="mailto:chloneda@gmail.com" title="E-Mail &rarr; mailto:chloneda@gmail.com" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://weibo.com/chloneda" title="Weibo &rarr; https://weibo.com/chloneda" rel="noopener" target="_blank"><i class="fa fa-fw fa-weibo"></i>Weibo</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="http://www.zhihu.com/people/chl_vip" title="知乎 &rarr; http://www.zhihu.com/people/chl_vip" rel="noopener" target="_blank"><i class="fa fa-fw fa-globe"></i>知乎</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://www.cnblogs.com/chloneda" title="博客园 &rarr; https://www.cnblogs.com/chloneda" rel="noopener" target="_blank"><i class="fa fa-fw fa-globe"></i>博客园</a>
                </span>
              
            </div>
          

          

          
          


	  <div id="music163player">
		<iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width="330" height="86" src="//music.163.com/outchain/player?type=2&id=5239700&auto=0&height=66"></iframe>
	  </div>

          
            
          
          

        </div>
      </div>

      
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
            
            
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#User类"><span class="nav-number">1.</span> <span class="nav-text">User类</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#UserDao类"><span class="nav-number">2.</span> <span class="nav-text">UserDao类</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#userDao-xml"><span class="nav-number">3.</span> <span class="nav-text">userDao.xml</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#mybatis-conf-xml"><span class="nav-number">4.</span> <span class="nav-text">mybatis-conf.xml</span></a></li></ol></div>
            

          </div>
        </div>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2018 – <span itemprop="copyrightYear">2020</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">chloneda</span>

  

  
</div>


  <div class="powered-by">由 <a href="https://hexo.io" class="theme-link" rel="noopener" target="_blank">Hexo</a> 强力驱动 v3.8.0</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 – <a href="https://theme-next.org" class="theme-link" rel="noopener" target="_blank">NexT.Mist</a> v7.0.0</div>




        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="post-meta-item-icon">
      <i class="fa fa-user"></i>
    </span>
    <span class="site-uv" title="总访客量">
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
    </span>
  

  
    <span class="post-meta-divider">|</span>
  

  
    <span class="post-meta-item-icon">
      <i class="fa fa-eye"></i>
    </span>
    <span class="site-pv" title="总访问量">
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
    </span>
  
</div>









        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

    

    
  </div>

  

<script>
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  <script src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>


  


  <script src="/js/src/utils.js?v=7.0.0"></script>

  <script src="/js/src/motion.js?v=7.0.0"></script>



  
  


  <script src="/js/src/schemes/muse.js?v=7.0.0"></script>




  
  <script src="/js/src/scrollspy.js?v=7.0.0"></script>
<script src="/js/src/post-details.js?v=7.0.0"></script>



  


  <script src="/js/src/bootstrap.js?v=7.0.0"></script>



  



  
  <script>
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url).replace(/\/{2,}/g, '/');
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x"></i></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x"></i></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://www.gstatic.com/firebasejs/4.6.0/firebase.js"></script>
  <script src="https://www.gstatic.com/firebasejs/4.6.0/firebase-firestore.js"></script>
  
  <script>
    (function () {

      firebase.initializeApp({
        apiKey: '',
        projectId: ''
      })

      function getCount(doc, increaseCount) {
        //increaseCount will be false when not in article page

        return doc.get().then(function (d) {
          var count
          if (!d.exists) { //has no data, initialize count
            if (increaseCount) {
              doc.set({
                count: 1
              })
              count = 1
            }
            else {
              count = 0
            }
          }
          else { //has data
            count = d.data().count
            if (increaseCount) {
              if (!(window.localStorage && window.localStorage.getItem(title))) { //if first view this article
                doc.set({ //increase count
                  count: count + 1
                })
                count++
              }
            }
          }
          if (window.localStorage && increaseCount) { //mark as visited
            localStorage.setItem(title, true)
          }

          return count
        })
      }

      function appendCountTo(el) {
        return function (count) {
          $(el).append(
            $('<span>').addClass('post-visitors-count').append(
              $('<span>').addClass('post-meta-divider').text('|')
            ).append(
              $('<span>').addClass('post-meta-item-icon').append(
                $('<i>').addClass('fa fa-users')
              )
              ).append($('<span>').text('阅读次数 ' + count))
          )
        }
      }

      var db = firebase.firestore()
      var articles = db.collection('articles')

      //https://hexo.io/docs/variables.html
      var isPost = '深入浅出Mybatis系列七-mapper映射文件配置之insert、update、delete'.length > 0
      var isArchive = '' === 'true'
      var isCategory = ''.length > 0
      var isTag = ''.length > 0

      if (isPost) { //is article page
        var title = '深入浅出Mybatis系列七-mapper映射文件配置之insert、update、delete'
        var doc = articles.doc(title)

        getCount(doc, true).then(appendCountTo($('.post-meta')))
      }
      else if (!isArchive && !isCategory && !isTag) { //is index page
        var titles = [] //array to titles

        var postsstr = '' //if you have a better way to get titles of posts, please change it
        eval(postsstr)

        var promises = titles.map(function (title) {
          return articles.doc(title)
        }).map(function (doc) {
          return getCount(doc)
        })
        Promise.all(promises).then(function (counts) {
          var metas = $('.post-meta')
          counts.forEach(function (val, idx) {
            appendCountTo(metas[idx])(val)
          })
        })
      }
    })()
  </script>


  

  

  
  <script>
    (function(){
      var bp = document.createElement('script');
      var curProtocol = window.location.protocol.split(':')[0];
      bp.src = (curProtocol === 'https') ? 'https://zz.bdstatic.com/linksubmit/push.js' : 'http://push.zhanzhang.baidu.com/push.js';
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
    })();
  </script>


  

  

  

  

  

  

  

  
  <style>
    .copy-btn {
      display: inline-block;
      padding: 6px 12px;
      font-size: 13px;
      font-weight: 700;
      line-height: 20px;
      color: #333;
      white-space: nowrap;
      vertical-align: middle;
      cursor: pointer;
      background-color: #eee;
      background-image: linear-gradient(#fcfcfc, #eee);
      border: 1px solid #d5d5d5;
      border-radius: 3px;
      user-select: none;
      outline: 0;
    }

    .highlight-wrap .copy-btn {
      transition: opacity .3s ease-in-out;
      opacity: 0;
      padding: 2px 6px;
      position: absolute;
      right: 4px;
      top: 8px;
    }

    .highlight-wrap:hover .copy-btn,
    .highlight-wrap .copy-btn:focus {
      opacity: 1
    }

    .highlight-wrap {
      position: relative;
    }
  </style>
  <script>
    $('.highlight').each(function(i, e) {
      var $wrap = $('<div>').addClass('highlight-wrap');
      $(e).after($wrap);
      $wrap.append($('<button>').addClass('copy-btn').append('复制').on('click', function(e) {
        var code = $(this).parent().find('.code').find('.line').map(function(i, e) {
          return $(e).text();
        }).toArray().join('\n');
        var ta = document.createElement('textarea');
        var range = document.createRange(); //For Chrome
        var sel = window.getSelection(); //For Chrome
        var yPosition = window.pageYOffset || document.documentElement.scrollTop;
        ta.style.top = yPosition + 'px'; //Prevent page scroll
        ta.style.position = 'absolute';
        ta.style.opacity = '0';
        ta.value = code;
        ta.textContent = code; //For FireFox
        ta.contentEditable = true;
        ta.readOnly = false;
        document.body.appendChild(ta);
        range.selectNode(ta);
        sel.removeAllRanges();
        sel.addRange(range);
        ta.setSelectionRange(0, code.length);
        var result = document.execCommand('copy');
        
        ta.blur(); //For iOS
        $(this).blur();
      })).on('mouseleave', function(e) {
        var $b = $(this).find('.copy-btn');
        setTimeout(function() {
          $b.text('复制');
        }, 300);
      }).append(e);
    })
  </script>


</body>
</html>
